package com.j.lemon.learn.flink.datastream;

import com.j.lemon.learn.flink.WordCount;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.List;

/**
 * 分区或窗口后， 滚动压缩每一个元素，形成新的一个元素。
 * 和dataset中 reduce的区别： dataset中的reduce只返回一个元素， datastream返回每次滚动的元素
 * 运行结果：
 * 5> WordCount{word='zhangsan', count=1}
 * 8> WordCount{word='lisi', count=3}
 * 8> WordCount{word='lisilisi', count=5}
 * 8> WordCount{word='lisilisilisi', count=6}
 * @author lijunjun
 */
public class ReduceOperator {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        KeyedStream<WordCount, String> keydStream = env.fromElements(
                new WordCount("zhangsan", 1),
                new WordCount("lisi", 3),
                new WordCount("lisi", 2),
                new WordCount("lisi", 1)).keyBy(new KeySelector<WordCount, String>() {
            @Override
            public String getKey(WordCount wordCount) throws Exception {
                return wordCount.getWord();
            }
        });
        DataStream<WordCount> dataStream = keydStream.reduce(new ReduceFunction<WordCount>() {
            @Override
            public WordCount reduce(WordCount wordCount, WordCount t1) throws Exception {
                wordCount.setWord(wordCount.getWord() + t1.getWord());
                wordCount.setCount(wordCount.getCount() + t1.getCount());
                return wordCount;
            }
        });
        dataStream.print();
        env.execute();

    }
}
